import { PageContainer, ProTable } from '@ant-design/pro-components';
import {Space,Input,Button,Popconfirm,message} from "antd"
import {useSelector,useDispatch} from "umi"
import {useState,useEffect} from "react"

export default function Type() {
  const [inpval,setInpVal] = useState('')
  const dispatch = useDispatch();
  const {typeList} = useSelector(state=>state.type)
  function confirm(row){
    console.log(row)
    const id = row._id;
    dispatch({
      type:'type/_deleteType',
      payload:{
        id
      }
    })
  }
  function handleChange(e){
    setInpVal(e.target.value)
  }
  function handleAdd(){
    console.log(inpval)
    if(inpval.trim()===''){
      message.warning('请填写新增类型')
      return 
    }
    // 判断该类型是否已经存在
    const resArr=typeList.filter(item=>{
      return item.typeName===inpval
    })
    if(resArr.length>0){
      message.warning('该类型已经存在请不要重复新增')
      return  
    }
    dispatch({
      type:'type/_addType',
      payload:{
        typeName:inpval
      }
    })
  }
  useEffect(()=>{
    if(typeList.length===0){
      dispatch({
        type:'type/_initList'
      })
    }else{
      console.log('面试题列表页有数据不用请求')
    }
  },[])
  const columns = [
    {
      title:'序号',
      key:'number',
      align:'center',
      render:(_,rows,index)=>{
        return index+1
      },
      width:'100px',


    },{
      title:'分类名称',
      key:'typeName',
      dataIndex:'typeName',
      align:'center',
    },{
      title:'操作',
      key:'options',
      width:'100px',
      render:(_,rows)=>{
        return (<Popconfirm
        title="删除类型"
        description="确定删除当前类型"
        okText="确定"
        cancelText="取消"
        onConfirm={() => {
          confirm(rows);
        }}
      >
        <Button type="link" size="small" >
          删除
        </Button>
      </Popconfirm>)
      }
    }
  ]
  return (<PageContainer>
     <Space.Compact
      style={{
        width: '400px',
        marginBottom:'20px'
      }}
    >
      <Input placeholder="请填写新增类型" value={inpval} onChange={handleChange} />
      <Button type="primary" onClick={handleAdd}>新增</Button>
    </Space.Compact>
    <ProTable 
    pagination={{
      defaultPageSize:5
    }}
    search={false} 
    toolbar={{title:'分类信息'}}
    dataSource={typeList}
    rowKey={(row)=>{return row._id
    }}
    columns={columns}
    ></ProTable>
  </PageContainer>);
}
